import axios from 'axios';
import { BASE_URL } from './config';
import { MessageBox, Notification } from 'element-ui';

const onRequest = (req) => {
  return req;
};
const onRequestError = (err) => {
  return Promise.reject(err);
};

const onResponse = (res) => {
  return Promise.resolve(res);
};
const onResponseError = (err) => {
  if (!err.response) {
    // network error
    MessageBox({
      message: '请检查你的网络，点击确定刷新页面。',
      title: '未知错误',
      type: 'error',
    }).then(() => {
      window.location.reload();
    });
  } else {
    const { status, data } = err.response;
    if (status === 400 || status === 422) {
      const { error_msg = "参数错误 请稍后尝试"} = err.response.data

      Notification.error({
        title: '格式错误',
        message: error_msg
      })
    } else if (status === 401) {
      const { error_msg = "您没有登录，无权操作." } = data
      // Authorization failed
      MessageBox({
        message: error_msg,
        title: '未授权',
        type: 'error',
      }).then(() => {
        window.location.href = '/login';
      });
    } else if (status === 403) {
      Notification.error({
        title: '权限不足',
        message: err.response.data.error_msg
      })
    } else if (status === 404) {
      Notification.error({
        title: `404 ${err.response.data.error_msg}`,
        message: '页面不存在'
      })
    } else if (status === 429) {
      Notification.error({
        title: `请求被拒绝`,
        message: '请注意频率'
      })
    } else if (status >= 500) {
      MessageBox({
        message: '服务器错误，请联系管理员。',
        title: '服务器错误',
        type: 'error',
      });
    } else {
      Notification.error({
        title: 'Internal Server Error',
        dangerouslyUseHTMLString: true,
        message: `<div style="width: 100%;word-wrap:break-word;word-break:break-all;">${data.error_msg || data.message}</div>`
      })
    }
  }
  return Promise.reject(err);
};

export const createAxios = () => {
  const config = {
    baseURL: BASE_URL,
    timeout: 60000,
    withCredentials: true,
  };
  const http = axios.create(config);
  http.interceptors.request.use(onRequest, onRequestError);
  http.interceptors.response.use(onResponse, onResponseError);
  return http;
};

export const http = createAxios();
